package com.xunyin.modules.mtstore.rest;


import com.xunyin.api.XunyinException;
import com.xunyin.constant.Constants;
import com.xunyin.enums.StatusEnum;
import com.xunyin.enums.YesOrNoEnum;
import com.xunyin.modules.mtstore.domain.MtStore;
import com.xunyin.modules.mtstore.service.StoreService;
import com.xunyin.modules.mtstore.service.dto.StoreDto;
import com.xunyin.modules.security.security.TokenUtil;
import com.xunyin.modules.security.security.vo.JwtUser;
import com.xunyin.pagination.PaginationRequest;
import com.xunyin.pagination.PaginationResponse;
import com.xunyin.utils.CommonUtilV;
import com.xunyin.utils.SecurityUtils;
import com.xunyin.utils.StringUtil;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 店铺管理类controller
 * <p>
 * Created by xunyinyunshang <3594419785@qq.com>
 * CopyRight 讯音云商 https://www.tonetn.com
 */
@Slf4j
@AllArgsConstructor
@Api(tags = "共享空间:店铺管理类")
@RestController
@RequestMapping("api/store")
public class BackendStoreController {

    /**
     * 店铺服务接口
     */
    private final StoreService storeService;
    private final TokenUtil tokenUtil;

    /**
     * 分页查询店铺列表
     *
     * @param request HttpServletRequest对象
     * @return 店铺列表
     */
    @RequestMapping(value = "/list")
    @CrossOrigin
    public ResponseEntity<PaginationResponse> list(HttpServletRequest request) {
        Integer page = request.getParameter("page") == null ? Constants.PAGE_NUMBER : Integer.parseInt(request.getParameter("page"));
        Integer pageSize = request.getParameter("pageSize") == null ? Constants.PAGE_SIZE : Integer.parseInt(request.getParameter("pageSize"));

        String storeId = request.getParameter("id");
        String storeName = request.getParameter("name");
        String storeStatus = request.getParameter("status");

/*        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }
        if (accountInfo.getStoreId() != null && accountInfo.getStoreId() > 0) {
            storeId = accountInfo.getStoreId().toString();
        }*/

        PaginationRequest paginationRequest = new PaginationRequest();
        paginationRequest.setCurrentPage(page);
        paginationRequest.setPageSize(pageSize);

        Map<String, Object> params = new HashMap<>();
        if (StringUtil.isNotEmpty(storeId)) {
            params.put("storeId", storeId);
        }
        if (StringUtil.isNotEmpty(storeName)) {
            params.put("name", storeName);
        }
        if (StringUtil.isNotEmpty(storeStatus)) {
            params.put("status", storeStatus);
        }
        JwtUser user = tokenUtil.getJwtUser(tokenUtil.getToken(request));
        if (!user.getRoleIdList().contains(Long.valueOf(1L))) {
            params.put("storeIdList", user.getStoreIdList());
        }

        paginationRequest.setSearchParams(params);
        PaginationResponse<MtStore> paginationResponse = storeService.queryStoreListByPagination(paginationRequest);

        return new ResponseEntity<>(paginationResponse, HttpStatus.OK);
        //return getSuccessResult(paginationResponse);
    }

    /**
     * 查询店铺列表
     */
    @RequestMapping(value = "/searchStoreByStoreId", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseEntity<Map<String, Object>> searchStoreByStoreId(HttpServletRequest request) {
        String token = request.getHeader("Access-Token");
        String storeId = request.getParameter("storeId") == null ? "" : request.getParameter("storeId");
        String storeName = request.getParameter("name") == null ? "" : request.getParameter("name");
        Map<String, Object> params = new HashMap<>();
//        if (StringUtil.isNotEmpty(storeId)) {
//            params.put("storeId", storeId);
//        }
        if (StringUtil.isNotEmpty(storeName)) {
            params.put("name", storeName);
        }
        JwtUser user = tokenUtil.getJwtUser(tokenUtil.getToken(request));
        if (!user.getRoleIdList().contains(Long.valueOf(1L))) {
            params.put("storeIdList", user.getStoreIdList());
        }
        params.put("status", StatusEnum.ENABLED.getKey());
        List<MtStore> storeList = storeService.queryStoresByParams(params);
        Map<String, Object> result = new HashMap<>();
        result.put("storeList", storeList);

        return new ResponseEntity<>(result, HttpStatus.OK);
        //return getSuccessResult(result);
    }

    /**
     * 查询店铺列表
     */
    @RequestMapping(value = "/searchStore", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseEntity<Map<String, Object>> searchStore(HttpServletRequest request) {
        String token = request.getHeader("Access-Token");
        Integer storeId = request.getParameter("storeId") == null ? 0 : Integer.parseInt(request.getParameter("storeId"));
        String storeName = request.getParameter("name") == null ? "" : request.getParameter("name");

        Map<String, Object> params = new HashMap<>();
/*        if (StringUtil.isNotEmpty(storeId)) {
            params.put("storeId", storeId);
        }*/
//        if(storeId>0){
//            params.put("storeId", storeId);
//        }
        if (StringUtil.isNotEmpty(storeName)) {
            params.put("name", storeName);
        }

        params.put("status", StatusEnum.ENABLED.getKey());
        List<MtStore> storeList = storeService.queryStoresByParams(params);
        JwtUser user = tokenUtil.getJwtUser(tokenUtil.getToken(request));
        if (!user.getRoleIdList().contains(Long.valueOf(1L)) && storeList != null) {
            storeList = storeList.stream().filter(item -> user.getStoreIdList().contains(item.getId())).collect(Collectors.toList());
        }
        Map<String, Object> result = new HashMap<>();
        result.put("storeList", storeList);

        return new ResponseEntity<>(result, HttpStatus.OK);
        //return getSuccessResult(result);
    }


    /**
     * 更新店铺状态
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateStatus")
    @CrossOrigin
    public ResponseEntity updateStatus(HttpServletRequest request, @RequestBody Map<String, Object> params) {
        String token = request.getHeader("Access-Token");
        String status = params.get("status") != null ? params.get("status").toString() : StatusEnum.ENABLED.getKey();
        Integer storeId = params.get("storeId") == null ? 0 : Integer.parseInt(params.get("storeId").toString());

/*        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }*/

        //String operator = accountInfo.getAccountName();
        String operator = SecurityUtils.getUsername();
        storeService.updateStatus(storeId, operator, status);

        return new ResponseEntity(HttpStatus.OK);
        //return getSuccessResult(true);
    }

    /**
     * 保存门店使用说明
     *
     * @param request HttpServletRequest对象
     * @return
     */
    @RequestMapping(value = "/saveInstr", method = RequestMethod.POST)
    @CrossOrigin
    public ResponseEntity saveInstr(HttpServletRequest request, @RequestBody Map<String, Object> params) {
        StoreDto storeInfo = new StoreDto();
        String storeId = params.get("id").toString();
        String instr = CommonUtilV.replaceXSS(params.get("instr").toString());
        storeInfo.setInstr(instr);
        if (StringUtil.isNotEmpty(storeId)) {
            storeInfo.setId(Integer.parseInt(storeId));
        } else {
            throw new XunyinException("门店id不能为空");
        }
        String operator = SecurityUtils.getUsername();
        storeInfo.setOperator(operator);
        MtStore mtStore = storeService.saveInstr(storeInfo);
        Map<String, Object> result = new HashMap();
        result.put("storeInfo", mtStore);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 保存店铺
     *
     * @param request HttpServletRequest对象
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @CrossOrigin
    public ResponseEntity saveHandler(HttpServletRequest request, @RequestBody Map<String, Object> params) {
        String token = request.getHeader("Access-Token");

        StoreDto storeInfo = new StoreDto();
        String storeId = params.get("id").toString();
        String storeName = CommonUtilV.replaceXSS(params.get("name").toString());
        String contact = CommonUtilV.replaceXSS(params.get("contact").toString());
        String phone = CommonUtilV.replaceXSS(params.get("phone").toString());
        String description = params.get("description") == null ? "" : CommonUtilV.replaceXSS(params.get("description").toString());
        String isDefault = params.get("isDefault") == null ? YesOrNoEnum.NO.getKey() : CommonUtilV.replaceXSS(params.get("isDefault").toString());
        String address = params.get("address") == null ? "" : CommonUtilV.replaceXSS(params.get("address").toString());
        String hours = params.get("hours") == null ? "" : CommonUtilV.replaceXSS(params.get("hours").toString());
        String latitude = params.get("latitude") == null ? "" : CommonUtilV.replaceXSS(params.get("latitude").toString());
        String longitude = params.get("longitude") == null ? "" : CommonUtilV.replaceXSS(params.get("longitude").toString());
        String wxMchId = params.get("wxMchId") == null ? "" : CommonUtilV.replaceXSS(params.get("wxMchId").toString());
        String wxApiV2 = params.get("wxApiV2") == null ? "" : CommonUtilV.replaceXSS(params.get("wxApiV2").toString());
        String status = params.get("status") != null ? params.get("status").toString() : StatusEnum.ENABLED.getKey();
        String image = params.get("image") == null ? "" : CommonUtilV.replaceXSS(params.get("image").toString());
        String provinceCode = params.get("provinceCode") == null ? "" : CommonUtilV.replaceXSS(params.get("provinceCode").toString());
        String cityCode = params.get("cityCode") == null ? "" : CommonUtilV.replaceXSS(params.get("cityCode").toString());
        String countyCode = params.get("countyCode") == null ? "" : CommonUtilV.replaceXSS(params.get("countyCode").toString());
        String orderCharge = params.get("orderCharge") == null ? "" : CommonUtilV.replaceXSS(params.get("orderCharge").toString());
        String startTimeNum = params.get("startTimeNum") == null ? "" : CommonUtilV.replaceXSS(params.get("startTimeNum").toString());

        // 美团点评开放平台密钥Key
        String dianpingAppkey = params.get("dianpingAppkey") == null ? "" : CommonUtilV.replaceXSS(params.get("dianpingAppkey").toString());

        // 美团点评开放平台密钥Secret
        String dianpingSecret = params.get("dianpingSecret") == null ? "" : CommonUtilV.replaceXSS(params.get("dianpingSecret").toString());

        //北极星团购门店Id
        String openShopUuid = params.get("openShopUuid") == null ? "" : CommonUtilV.replaceXSS(params.get("openShopUuid").toString());

        // 抖音门店POI_ID
        String poiId = params.get("poiId") == null ? "" : CommonUtilV.replaceXSS(params.get("poiId").toString());

        // 抖音门店client_key
        String clientKey = params.get("clientKey") == null ? "" : CommonUtilV.replaceXSS(params.get("clientKey").toString());

        // 抖音门店client_secret
        String clientSecret = params.get("clientSecret") == null ? "" : CommonUtilV.replaceXSS(params.get("clientSecret").toString());

        log.info("image:" + image);
        if ((StringUtil.isEmpty(latitude) || StringUtil.isEmpty(longitude)) && StringUtil.isNotEmpty(address)) {
            Map<String, Object> latAndLng = CommonUtilV.getLatAndLngByAddress(address);
            latitude = latAndLng.get("lat").toString();
            longitude = latAndLng.get("lng").toString();
        }

/*        if (accountInfo.getStoreId() != null && accountInfo.getStoreId() > 0) {
            storeId = accountInfo.getStoreId().toString();
        }*/

        storeInfo.setName(storeName);
        storeInfo.setContact(contact);
        storeInfo.setPhone(phone);
        storeInfo.setDescription(description);
        storeInfo.setIsDefault(isDefault);
        storeInfo.setAddress(address);
        storeInfo.setHours(hours);
        storeInfo.setLatitude(latitude);
        storeInfo.setLongitude(longitude);
        storeInfo.setStatus(status);
        storeInfo.setWxMchId(wxMchId);
        storeInfo.setWxApiV2(wxApiV2);
        storeInfo.setImage(image);
        storeInfo.setProvinceCode(provinceCode);
        storeInfo.setCityCode(cityCode);
        storeInfo.setCountyCode(countyCode);
        storeInfo.setOrderCharge(Integer.parseInt(orderCharge));
        storeInfo.setStartTimeNum(Integer.parseInt(startTimeNum));

        storeInfo.setDianpingAppkey(dianpingAppkey);
        storeInfo.setDianpingSecret(dianpingSecret);
        storeInfo.setOpenShopUuid(openShopUuid);
        storeInfo.setPoiId(poiId);
        storeInfo.setClientKey(clientKey);
        storeInfo.setClientSecret(clientSecret);

        if (StringUtil.isEmpty(storeName)) {
            throw new XunyinException("店铺名称不能为空");
            //return getFailureResult(201, "店铺名称不能为空");
        } else {
            if (!StringUtil.isNotEmpty(storeName)) {
                StoreDto tempDto = storeService.queryStoreByName(storeName);
                if (null != tempDto && tempDto.getName().equals(storeName) && !tempDto.getId().equals(storeId)) {
                    throw new XunyinException("该店铺名称已经存在");
                    //return getFailureResult(201, "该店铺名称已经存在");
                }
            }
        }

        // 修改店铺
        if (StringUtil.isNotEmpty(storeId)) {
            storeInfo.setId(Integer.parseInt(storeId));
        }

        // String operator = accountInfo.getAccountName();
        String operator = SecurityUtils.getUsername();
        storeInfo.setOperator(operator);
        storeService.saveStore(storeInfo);

        return new ResponseEntity(HttpStatus.OK);
        //return getSuccessResult(true);
    }

    /**
     * 店铺信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseEntity<Map<String, Object>> getStoreInfo(HttpServletRequest request, @PathVariable("id") Integer id) {
        String token = request.getHeader("Access-Token");

        StoreDto storeInfo = storeService.queryStoreDtoById(id);

        Map<String, Object> result = new HashMap<>();
        result.put("storeInfo", storeInfo);

        return new ResponseEntity<>(result, HttpStatus.OK);
    }

}
